package com.postracker.initdatabase.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import com.postracker.initdatabase.db.action.DbStatements;
import com.postracker.initdatabase.db.exception.DataBaseException;

public class DataBase {

	private static final int DEFAULT_TIMEOUT = 30;

	private String connectionDriver;
	private String connectionUrl;
	private Connection connection;
	private Statement statement;

	protected DataBase(String driver, String url) {
		connectionDriver = driver;
		connectionUrl = url;
		loadConnectionDriver();
	}

	private void loadConnectionDriver() {
		try {
			Class.forName(connectionDriver);
		} catch (ClassNotFoundException e) {
			throw new DataBaseException("Connection Driver not found"
					+ connectionDriver, e);
		}
	}

	public void openConnection() {
		try {
			connection = DriverManager.getConnection(connectionUrl);
		} catch (SQLException e) {
			throw new DataBaseException(e);
		}
	}

	public void executeAllStmt(DbStatements statements) {
		for (String instruction : statements.getStatements()) {
			executeStmt(instruction);
		}
	}

	private void executeStmt(String instruction) {
		try {
			createNewStatement();
			statement.executeUpdate(instruction);
		} catch (SQLException e) {
			throw new DataBaseException(e);
		}
	}

	private void createNewStatement() {
		try {
			assertConnectionOpen();
			statement = connection.createStatement();
			statement.setQueryTimeout(DEFAULT_TIMEOUT);
		} catch (SQLException e) {
			throw new DataBaseException(e);
		}
	}

	public void closeConnection() {
		try {
			assertConnectionOpen();
			connection.close();
		} catch (SQLException e) {
			throw new DataBaseException(
					"Error trying to close the database connection", e);
		}
	}

	private void assertConnectionOpen() throws SQLException {
		if (connection == null || connection.isClosed()) {
			throw new DataBaseException(
					"The connection to the DataBase has not been opened yet");
		}
	}
}
